package com.four.bmm.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ImageServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//生成验证码，生成bufferdimage
		BufferedImage bi = new BufferedImage(68, 32, BufferedImage.TYPE_INT_RGB);//定义图片的高度和宽度
		Graphics graphics=bi.getGraphics(); //画一个图片
		Color color=new Color(200, 150, 255);
		graphics.setColor(color);
		graphics.fillRect(0, 0, 68, 32);
		
		List list=new ArrayList();
		char[] num="1234567890".toCharArray();
		char[] strUpper="ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
		char[] strLower="abcdefghijklmnopqrstuvwxyz".toCharArray();
		
		for (int i = 0; i < num.length; i++) {
			list.add(num[i]);
		}
		for (int i = 0; i < strUpper.length; i++) {
			list.add(strUpper[i]);
		}
		for (int i = 0; i < strLower.length; i++) {
			list.add(strLower[i]);
		}
		Object[] ch=list.toArray();

		//char[] ch="1234567890".toCharArray(); //生成随机数

		int len=ch.length,index;
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		for (int i = 0; i < 4; i++) {
			index=random.nextInt(len); //生成随即的字符，从char数组中获取，指定数组的长度
			graphics.setColor(
					new Color(
							random.nextInt(88), 
							random.nextInt(188), 
							random.nextInt(255)));
			graphics.setFont(new Font("italic", Font.ITALIC, 20));
			graphics.drawString(ch[index]+"", (i*15)+3, 18);
			
			sb.append(ch[index]);
		}
		
		request.getSession().setAttribute("piccode", sb.toString());	//将sb对象转为string类型进行验证
		ImageIO.write(bi, "JPG", response.getOutputStream());
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doGet(request, response);
	}

}
